package com.tjtt.tdm.system.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tjtt.common.utils.StringUtil;
import com.tjtt.tdm.base.BaseAction;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.base.ParamBean;
import com.tjtt.tdm.base.PubMethod;
import com.tjtt.tdm.base.StaticDataCache;
import com.tjtt.tdm.exception.ServiceException;
import com.tjtt.tdm.portlet.bean.SysPortlet;
import com.tjtt.tdm.portlet.service.PortletService;
import com.tjtt.tdm.system.bean.Menu;
import com.tjtt.tdm.system.bean.Organization;
import com.tjtt.tdm.system.bean.Role;
import com.tjtt.tdm.system.bean.Rolemenu;
import com.tjtt.tdm.system.bean.Rolemenuoperation;
import com.tjtt.tdm.system.bean.UserRole;
import com.tjtt.tdm.system.service.FineGrainedAuthorityService;
import com.tjtt.tdm.system.service.LogService;
import com.tjtt.tdm.system.service.MenuService;
import com.tjtt.tdm.system.service.RoleService;
import com.tjtt.tdm.system.service.UserRoleService;
import com.tjtt.tdm.system.service.UserService;

/**
 * 角色管理
 * 
 * @author leung
 * 
 */
public class RoleAction extends BaseAction {
	private Organization organization;
	public Organization getOrganization() {
		return organization;
	}
	public void setOrganization(Organization organization) {
		this.organization = organization;
	}
	/**
	 * 系统角色树形展示
	 * @return
	 * @throws ServiceException List
	 * @author 詹晓梅
	 * @date 2013-1-23 下午02:42:31 
	 */
	public List getRoleTree() throws ServiceException{
		List<Role> findRoleById = roleService.findRoleTree(null);
		return findRoleById;
	}
	/**
	 * 添加角色--tree
	 * @throws ServiceException void
	 * @author 詹晓梅
	 * @date 2013-1-25 下午03:41:25
	 */
	public void addRole() throws ServiceException{
		Long parentid = Long.parseLong(this.getRequest().getParameter("parentid"));
		String rolename = this.getRequest().getParameter("rolename");
		String rolelabel = this.getRequest().getParameter("rolelabel");
		String roledesc = this.getRequest().getParameter("roledesc");
		try{
			PrintWriter out = getResponse().getWriter();
			//Role roles = roleService.findRoleByName(rolename);
			//if(roles !=null){
				//getRequest().setAttribute("message", "该角色名称已存在");
				//out.print("{\"ajaxResult\":\"have\"}");
			//}else{
				Role role = new Role();
				role.setParentid(parentid);
				role.setRolename(rolename.toString().trim());
				role.setRolelabel(rolelabel.toString().trim());
				role.setRoledesc(roledesc.toString().trim());
				roleService.saveRole(role);
				out.print("{\"ajaxResult\":\"success\"}");
				getRequest().setAttribute("message", "添加成功!");
				logService.saveLogInfo(this.getLogBase(),"系统管理", "角色管理", "角色信息添加成功",3);			
		//	}
		}catch (Exception e) {
			getRequest().setAttribute("message", "添加失败!");
			logService.saveLogInfo(this.getLogBase(),"系统管理", "角色管理", "角色信息添加失败",3);			
		}
	}
	
	/**
	 * 获取“试验室主任”信息
	 *  void
	 * @author Zhanxm
	 * @date Sep 10, 2014 5:48:13 PM
	 */
	public void getRoleInfo230(){
		setContentType();
		try{
			PrintWriter out = getResponse().getWriter();
			String sql = "select t.rolename,t.rolelabel,t.roledesc from sys_role t where t.roleid = 230 ";
			List listrole = roleService.queryListBySql(sql);
			if(!listrole.isEmpty()){
				String rolename =  (((Object [])listrole.get(0))[0]+"").toString();
				String rolelabel = (((Object [])listrole.get(0))[1]+"").toString();
				String roledesc = (((Object [])listrole.get(0))[2]+"").toString();
				out.print("{\"rolename\":\""+rolename+"\",\"rolelabel\":\""+rolelabel+"\",\"roledesc\":\""+roledesc+"\"}");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	  /**
	   * 跳转到角色信息修改页面
	   * @return String
	   * @author 詹晓梅 
	   * @date 2013-1-28 上午10:02:11
	   */
	public String toupdateRoleExec(){
		  role=roleService.findRoleById(roleId);
		  return SUCCESS;  
	}
	/**
	 * 角色修改--tree
	 * @throws Exception void
	 * @author 詹晓梅
	 * @date 2013-1-28 上午10:04:37
	 */
	public void updateRoleExec() throws Exception{
		try{
			setContentType();
			PrintWriter out = getResponse().getWriter();	
			
			Long roleId = Long.parseLong(this.getRequest().getParameter("roleId"));
			String rolename =getRequest().getParameter("rolename");
			Long parentid = Long.parseLong(getRequest().getParameter("parentid"));
			String rolelabel = getRequest().getParameter("rolelabel");
			String roledesc = getRequest().getParameter("roledesc");
			 role = roleService.findRoleById(roleId);
			//String rName = roles.getRolename();
				role.setRolename(rolename);
				role.setRolelabel(rolelabel);
				role.setRoledesc(roledesc);
				roleService.updateRole(role);
				out.print("{\"ajaxResult\":\"success\"}");
				getRequest().setAttribute("message", "修改成功!");
				logService.saveLogInfo(this.getLogBase(),"系统管理", "角色管理", "角色信息修改成功",3);
		
		}catch (Exception e) {
			e.printStackTrace();
			getRequest().setAttribute("message", "修改失败!");
			logService.saveLogInfo(this.getLogBase(),"系统管理", "角色管理", "角色信息修改失败",3);
		}	
	}
	/**
	 * update
	 * @throws Exception void
	 * @author 詹晓梅
	 * @date 2013-1-30 上午09:13:18
	 */
	public void updateRole() throws Exception{
			Long roleIds = Long.parseLong(this.getRequest().getParameter("roleId"));
			Long parentid = Long.parseLong(this.getRequest().getParameter("parentid"));
			String name =getRequest().getParameter("name");
			String labels = getRequest().getParameter("labels");
			String descs = getRequest().getParameter("descs");
			role = roleService.findRoleById(roleId);
			role.setRoleid(roleIds);
			role.setParentid(parentid);
			role.setRolename(name);
			role.setRolelabel(labels);
			role.setRoledesc(descs);
			PrintWriter out = getResponse().getWriter();		
			roleService.updateRole(role);
			out.print("{\"ajaxResult\":\"success\"}");
			logService.saveLogInfo(this.getLogBase(),"系统管理", "角色管理", "角色信息更新成功！",3);
			
			out.flush();
			out.close();		
				
	}
	
	/**
	 * 角色删除--tree
	 * @return
	 * @throws IOException
	 * @throws ServiceException String
	 * @author 詹晓梅
	 * @date 2013-1-28 上午10:04:52
	 */
	public String delRoleExec() throws IOException, ServiceException {
		setContentType();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		PrintWriter out = getResponse().getWriter();
		try{
			paramMap.put("roleid", roleId);
			if (userService.getTotalCountByRoleId(paramMap).intValue() > 0) {
				getRequest().setAttribute("message", "存在用户关联，不能删除！");
				throw new ServiceException(getText("role.bind"));
			}if (userService.getCroleByRoleId(paramMap).intValue() > 0) {
				getRequest().setAttribute("message", "存在子节点，不能删除！");
				throw new ServiceException(getText("role.bind"));
			}
			roleService.delRole(roleId);
			Long roleId = this.getUser().getRoleId();
			StaticDataCache.refreshData(fgaService, roleId);
			out.print("{\"ajaxResult\":\"success\"}");
			logService.saveLogInfo(this.getLogBase(), "系统管理", "角色管理", "成功删除一条角色记录",3);
			return null;
		}catch (Exception e){
			e.printStackTrace();
			out.print("{\"ajaxResult\":\"error\"}");
			logService.saveLogInfo(this.getLogBase(), "系统管理", "角色管理", "删除角色失败",3);
			return null;
		}
	}
	
	/**
	 * 查询名称是否存在
	 * @throws Exception void
	 * @author 詹晓梅
	 * @date 2013-1-28 上午09:56:10
	 */
		public void getRoleName() throws Exception{
			PrintWriter out = getResponse().getWriter();
			try{
				String rName = StringUtil.encodingUrl(getRequest().getParameter("rolename"));
				String old ="";// StringUtil.encodingUrl(getRequest().getParameter("old"));
				if(getRequest().getParameter("old") !=null && !"".equals(getRequest().getParameter("old"))){
				    old = StringUtil.encodingUrl(getRequest().getParameter("old"));
				}if(rName.equals(old)){
					out.print("{\"result\":\"success\"}");
				}else{
					Role role = roleService.findRoleByName(rName);
					if(role == null){
						out.print("{\"result\":\"success\"}");
					}else{
						out.print("{\"result\":\"false\"}");
					}
				}
				
			}catch (Exception e) {
				e.printStackTrace();
				out.print("{\"result\":\"false\"}");
			}
		}
		/**
		 * 用户管理角色查询
		 * @return null
		 * @throws IOException
		 * @throws ServiceException
		 */
		public String searchUserRoleExec() throws IOException, ServiceException {
			setContentType();
			
			PrintWriter out = getResponse().getWriter();
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			if (StringUtils.isNotEmpty(rolename)) {
				rolename = StringUtil.encodingUrl(rolename);
				ParamBean p = new ParamBean();
				p.setParam("rolename");
				p.setExpression(" like ");
				p.setValue("%" + rolename + "%");
				paramMap.put("rolename", p);
			}
			String toIds = this.getRequest().getParameter("toIds");
			String fromIds = this.getRequest().getParameter("fromIds");
			if(StringUtils.isNotEmpty(toIds)){
				String[] ids = toIds.split(",");
				Long[] roleIds = new Long[ids.length];
				for(int i=0;i<ids.length;i++){
					roleIds[i] = Long.valueOf(ids[i]);
				}
				ParamBean p = new ParamBean();
				p.setParam("roleid");
				p.setExpression(" not ");
				p.setValue(roleIds);
				paramMap.put("roleid", p);
			}
			
			if(StringUtils.isNotEmpty(fromIds)){
				String[] ids = fromIds.split(",");
				Long[] roleIds = new Long[ids.length];
				for(int i=0;i<ids.length;i++){
					roleIds[i] = Long.valueOf(ids[i]);
				}
				paramMap.put("roleid", roleIds);
			}
			Map fimap = getPagerMap();
			int start = rows * ( Integer.parseInt((fimap.get("page").toString())) - 1); //开始的记录
			long totalCount = roleService.getTotalCount(paramMap);
			List<Role> roles = roleService.findRoles(paramMap, totalCount, start, rows, sidxs, sord);
			JSONObject result = new JSONObject();
			JSONArray rolesJson = JSONArray.fromObject(roles);
			result.put("records", totalCount);
			result.put("roles", rolesJson);
			result.put("page", page); //总页数);
			result.put("total", (totalCount + rows - 1) / rows);
			//System.out.println(result.toString());
			out.write(result.toString());
			return null;
		}
		public void queryUserListExc(){
			try{
			Map<String, String> filterMap = getPagerMap();
			//Long roleid = Long.parseLong(getRequest().getParameter("roleid"));
			String roleid = getRequest().getParameter("roleid");
			String toIds = this.getRequest().getParameter("toIds");
			String[] viewArray = {"userid","username","org_id","org_name"};
			String returnStr = "";
			String username = getRequest().getParameter("username");
			String orgId = getRequest().getParameter("orgId");
			if(username !=null && !"".equals(username)){
				username = StringUtil.encodingUrl(username);
				username = StringUtil.escapeString(username);
			}
			if(orgId != null && !"".equals(orgId)){
				orgId = StringUtil.encodingUrl(orgId);
				orgId = StringUtil.escapeString(orgId);
			}
			filterMap.put("username", username);
			filterMap.put("orgId", orgId);
			filterMap.put("toIds", toIds);
			if(roleid != null && !roleid.equals("")){
				PageResult result = roleService.queryUserList(Long.parseLong(roleid), filterMap);
				returnStr = getColumnJson(result, viewArray);
			}else{
				PageResult result = roleService.queryUserList(Long.parseLong("5"), filterMap);
				returnStr = getColumnJson(result, viewArray);
			}
			//PageResult result = roleService.queryUserList(roleid, filterMap);
			//returnStr = getColumnJson(result, viewArray);
			setContentType();
			PrintWriter out = getResponse().getWriter();
			System.out.println(returnStr);
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
		/**
		 * 角色下人员
		 *  void
		 * @author 詹晓梅
		 * @date 2013-1-30 下午07:34:26
		 */
		@SuppressWarnings("unchecked")
		public void searchUserByRole(){
			try{ 
			Map filterMap = new HashMap();//存储参数的map
			filterMap.put("page",1);
			filterMap.put("rows",9999999);
			filterMap.put("sidx", "org_id");
			filterMap.put("sord", "asc");
			Long roleid = Long.parseLong(getRequest().getParameter("roleid"));
			String[] viewArray = {"userid","username","loginname","org_name"};
			String returnStr = "";
			
			//查询出所有数据
			PageResult result = roleService.searchUserByRole(roleid, filterMap);
			returnStr = getColumnJsonAll(result, viewArray);
			
			setContentType();
			PrintWriter out = getResponse().getWriter();
			System.out.println(returnStr);
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
		
		public String getColumnJsonAll(PageResult result,String[] viewArray){
		
			int totalRows = result.getRowCount(); //所有的行数
			int rowsInt= totalRows;
			int totalPages = 0; //总页数
            if(rowsInt!=0){
            	totalPages =(totalRows + rowsInt - 1) / rowsInt;
            }
			List rowAll = result.getData();   //查询出的所有记录
			JSONObject obj = new JSONObject();
			obj.put("page", "1");
			obj.put("total",totalPages);
			obj.put("records",""+totalRows);
			JSONArray lineitemArray = new JSONArray(); 
			Iterator it = rowAll.iterator();
			while (it.hasNext()) { 
				Object[] objlist = (Object[]) it.next();
				lineitemArray.add(getColumnValue(objlist,viewArray));
			} 
			obj.put("rows", lineitemArray);
			return obj.toString();
		}
	/**
	 * 根据角色查询人员
	 */
	public void queryUserByRole(){
			try{ 
			Map<String, String> filterMap = getPagerMap();
			String roleid = getRequest().getParameter("roleid");
			String orgId = getRequest().getParameter("orgId");
			String userName = getRequest().getParameter("userName");
			String userLoginName = getRequest().getParameter("userLoginName");
			String[] viewArray = {"userid","username","userloginname","org_id","org_name"};
			String returnStr = "";
			if(userName !=null && !"".equals(userName)){
				userName = StringUtil.encodingUrl(userName);
			}
			if(userLoginName !=null && !"".equals(userLoginName)){
				userLoginName = StringUtil.encodingUrl(userLoginName);
			}
			filterMap.put("orgId",orgId);
			filterMap.put("userName",userName);
			filterMap.put("userLoginName",userLoginName);
			//查询出所有数据
			PageResult result = roleService.queryUserByRole(roleid, filterMap);
			returnStr = getColumnJson(result, viewArray);
			
			setContentType();
			PrintWriter out = getResponse().getWriter();
			System.out.println(returnStr);
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public String saveUserToRole() throws Exception{
		PrintWriter out = getResponse().getWriter();
		try{
			UserRole userRole = new UserRole();
			
			roleService.savaUserToRole(userRole);
			out.print("{\"ajaxResult\":\"success\"}");
			logService.saveLogInfo(getLogBase(), "系统管理", "角色管理", "添加成功!",3);
			getRequest().setAttribute("message", "添加成功!");			
			return SUCCESS;
		}catch (Exception e) {
			e.printStackTrace();
			out.print("{\"ajaxResult\":\"error\"}");
			getRequest().setAttribute("message", "添加失败!");
			logService.saveLogInfo(getLogBase(), "系统管理", "角色管理", "添加失败!",3);	
			 return null;
		}
		
	}

	/**
	 * 角色菜单查询
	 * 
	 * @return
	 * @throws ServiceException
	 * @throws IOException
	 */

	public String roleMenuExec() throws ServiceException, IOException {
		System.out.println("roleId:"+roleId);
		StringBuilder checkdSbd = new StringBuilder();
		;// 新添加语句
		String checkdStr = "";
		List<Menu> menuList = menuService.getAllMenu();
		List<Rolemenu> rolemenuList = roleService.getRolemenuByRoleId(roleId);
		// String roleMenuContent = createTree(menuList);
		String roleMenuContent = testbuliderTree(menuList, checkdSbd);// 新添加语句
		checkdStr = getCheckedMenu(rolemenuList) + checkdSbd.toString();// 新添加语句
		this.getRequest().setAttribute("roleMenuContent", roleMenuContent);
		// getRequest().setAttribute("checkedMenu",
		// getCheckedMenu(rolemenuList)); 原语句
		getRequest().setAttribute("checkedMenu", checkdStr); // 新添加语句
		getRequest().setAttribute("roleId", roleId);
		return SUCCESS;
	}

	private String getCheckedMenu(List<Rolemenu> rolemenuList) {
		if (rolemenuList != null) {
			StringBuilder sb = new StringBuilder(",");
			for (Rolemenu rolemenu : rolemenuList) {
				sb.append(rolemenu.getMenuid());
				sb.append(",");
			}
			return sb.toString();
		} else {
			return "";
		}
	}

	private String createTree(List<Menu> menuList) throws ServiceException {
		HashMap<Long, String> childrenArray = new HashMap<Long, String>();
		// Map buttonMap=getRoleButtons();
		StringBuilder sb = new StringBuilder();
		sb.append("var rows={");
		for (int i = 0; i < menuList.size(); i++) {
			Menu menu = menuList.get(i);
			Long parentid = 0L;
			if (menu.getParentid() != 1) {
				parentid = menu.getParentid();
			}
			String children = (String) childrenArray.get(parentid);
			if (children == null) {
				children = "'" + menu.getMenuid() + "',";
			} else {
				children = children + "'" + menu.getMenuid() + "',";
			}
			childrenArray.put(parentid, children);
			if (i != 0) {
				sb.append(",");
			}
			sb.append("'");
			sb.append(menu.getMenuid());
			sb.append("':{'id':'");
			sb.append(menu.getMenuid());
			sb.append("','pid':'");
			sb.append(menu.getParentid().intValue() == 1 ? 0 : menu
					.getParentid().intValue());
			sb.append("','title':'");
			sb.append(menu.getMenuname());
			sb.append("'}");
		}
		sb.append("};");

		StringBuilder rowsPidIndex = new StringBuilder();
		Iterator<Long> iterator = childrenArray.keySet().iterator();
		while (iterator.hasNext()) {
			Long parentid = iterator.next();
			String children = childrenArray.get(parentid);
			rowsPidIndex.append("rowsPidIndex[");
			rowsPidIndex.append(parentid);
			rowsPidIndex.append("]=new Array(");
			rowsPidIndex.append(children.substring(0, children.length() - 1));
			rowsPidIndex.append(");");
		}
		return sb.toString() + rowsPidIndex.toString();
	}

	
	/**
	 * 保存角色菜单关系
	 * 
	 * @return
	 * @throws ServiceException
	 * @throws IOException
	 */
	public String saveRoleMenuExec() throws ServiceException, IOException {
		setContentType();
		PrintWriter out = getResponse().getWriter();
		String[] menuIdsStr = menuIds.split(",");
		List<Long> menuIds = new ArrayList<Long>();
		List roleButtons = new ArrayList();
		Rolemenuoperation buttonModel = null;
		for (String menuIdStr : menuIdsStr) {
			if (StringUtils.isNotEmpty(menuIdStr.trim())) {
				if (menuIdStr.indexOf("&&") == -1) {
					Long menuId = new Long(menuIdStr.trim());
					// Menu menu = menuService.getMenuById(menuId);
					// if(menu.getChildrennum().intValue() == 0){
					// menuIds.add(menuId);
					// }
					menuIds.add(menuId);
				} else {

					buttonModel = new Rolemenuoperation();
					String[] ids = menuIdStr.split("&&");
					buttonModel.setMenueid(Long.valueOf(ids[0]));
					buttonModel.setOpratingbuttonid(Long.valueOf(ids[1]));
					buttonModel.setRoleid(roleId);
					roleButtons.add(buttonModel);
				}
			}
		}

		fgaService.updateRoleMenuByRoleId(roleId, menuIds, roleButtons);
		Long roleId=   this.getUser().getRoleId();
		StaticDataCache.refreshData(fgaService, roleId);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("success", true);
		out.write(jsonObject.toString());
		return null;
	}
	


	/**
	 * 该方法暂时作为原createTree(List<Menu> menuList)的替代方法
	 * 
	 * @param menuList
	 * @param ischeckedStr
	 * @return
	 * @throws ServiceException
	 */
	public String testbuliderTree(List<Menu> menuList,
			StringBuilder ischeckedStr) throws ServiceException {

		HashMap<Long, String> childrenArray = new HashMap<Long, String>();
		List resultList = this.fgaService.getRoleButtons(roleId);
		 StaticDataCache.getMenuButtons(resultList, roleId);
		Map buttonMenumap =StaticDataCache.roleMenuButtonMap.get(roleId);

		StringBuilder sb = new StringBuilder();
		sb.append("var rows={");
		for (int i = 0; i < menuList.size(); i++) {
			Menu menu = menuList.get(i);
			Long parentid = 0L;
			List buttonList;

			if (menu.getParentid() != 1) {
				parentid = menu.getParentid();
			}
			String children = (String) childrenArray.get(parentid);
			if (children == null) {
				children = "'" + menu.getMenuid() + "',";
			} else {
				children = children + "'" + menu.getMenuid() + "',";
			}
			childrenArray.put(parentid, children);
			if (i != 0) {
				sb.append(",");
			}
			sb.append("'");
			sb.append(menu.getMenuid());
			sb.append("':{'id':'");
			sb.append(menu.getMenuid());
			sb.append("','pid':'");
			sb.append(menu.getParentid().intValue() == 1 ? 0 : menu
					.getParentid().intValue());
			sb.append("','title':'");
			sb.append(menu.getMenuname());
			sb.append("'}");

			if (buttonMenumap.size() != 0
					&& buttonMenumap.containsKey(menu.getMenuid())) {

				buttonList = (List) buttonMenumap.get(menu.getMenuid());
				for (int j = 0; j < buttonList.size(); j++) {
					Map buttonElement = (Map) buttonList.get(j);
					BigDecimal id = (BigDecimal) buttonElement
							.get("opratingbuttonid");
					String butonName = (String) buttonElement.get("buttonname");
					String ischecked = (String) buttonElement.get("case");
					String shadowId = menu.getMenuid() + "&&" + id; // MENUBUTTON的影子ID，这是为了可以通过这个id明确知道是不是button的数据，并且可以从中分离出button与menu的id出来，以便增删改

					sb.append(",");

					sb.append("'");
					sb.append(shadowId);
					sb.append("':{'id':'");
					sb.append(shadowId);
					sb.append("','pid':'");
					sb.append(menu.getMenuid().intValue() == 1 ? 0 : menu
							.getMenuid().intValue());
					sb.append("','title':'");
					sb.append(butonName);
					sb.append("'}");

					children = (String) childrenArray.get(menu.getMenuid());
					if (children == null) {
						children = "'" + shadowId + "',";
					} else {
						children = children + "'" + shadowId + "',";
					}
					childrenArray.put(menu.getMenuid(), children);

					if ("true".equals(ischecked)) {
						ischeckedStr.append(shadowId + ",");
					}
				}

			}
		}
		sb.append("};");

		StringBuilder rowsPidIndex = new StringBuilder();
		Iterator<Long> iterator = childrenArray.keySet().iterator();
		while (iterator.hasNext()) {
			Long parentid = iterator.next();
			String children = childrenArray.get(parentid);
			rowsPidIndex.append("rowsPidIndex[");
			rowsPidIndex.append(parentid);
			rowsPidIndex.append("]=new Array(");
			rowsPidIndex.append(children.substring(0, children.length() - 1));
			rowsPidIndex.append(");");
		}
		return sb.toString() + rowsPidIndex.toString();

	}
 
	public void updatePortlet(){
		try {
			String roleid = getRequest().getParameter("roleId");
			String portletList = getRequest().getParameter("portletList");
			 role = roleService.findRoleById(Long.parseLong(roleid));
			 if(!StringUtils.isEmpty(portletList)){
				 role.setPortletList(portletList.substring(0,portletList.length()-1));
			 }else{
				 role.setPortletList(null);
			 }
			 roleService.updateRole(role);
			 PrintWriter out = PubMethod.GetPrintWriter(); 
			 out.print("{\"ajaxResult\":\"success\"}");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取门户数据
	 */
	public void getPortletList(){
		try {
			StringBuffer sb = new StringBuffer();
			WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());  
			PortletService portletService =  (PortletService)factory.getBean("portletService");
			List<SysPortlet> list = portletService.getAllPortlet();
			String roleid = getRequest().getParameter("roleId");
			Role roles = roleService.findRoleById(Long.parseLong(roleid));
			String portletList = roles.getPortletList();
			if(StringUtils.isEmpty(portletList)){
				for (int i = 0; i < list.size(); i++) {
					SysPortlet portlet = list.get(i);
					if(null != portlet.getState() && !portlet.getState().isEmpty() && "正常".equals(portlet.getState())){
							sb.append("<input type=\"checkbox\" name=\"portletList\" value=\""+portlet.getId()+"\"/>"+portlet.getPortletName()+"<br>");
					}
					
				}
			}else{
				for (int i = 0; i < list.size(); i++) {
					SysPortlet portlet = list.get(i);
					if(null != portlet.getState() && !portlet.getState().isEmpty() && "正常".equals(portlet.getState())){
						if((","+portletList+",").contains(","+portlet.getId()+",")){
							sb.append("<input type=\"checkbox\" style=\"width:15px\" name=\"portletList\" checked=\"checked\" value=\""+portlet.getId()+"\" id=\"checkboxFiveInput"+portlet.getId()+"\"/>"+portlet.getPortletName()+"<br>");
						}else{
							sb.append("<input type=\"checkbox\" style=\"width:15px\" name=\"portletList\" value=\""+portlet.getId()+"\" id=\"checkboxFiveInput"+portlet.getId()+"\"/>"+portlet.getPortletName()+"<br>");
						}
					}
				}
			}
			setContentTypeHtml();
			PrintWriter out = getResponse().getWriter();
			out.print(sb.toString());			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**分页变量*/
	private int page;
	private int rows;
	private String sidxs;
	private String sord;
	
	private FineGrainedAuthorityService fgaService = null;
	
	
	
	
	private static final Log log = LogFactory.getLog(RoleAction.class);

	private static final long serialVersionUID = 1L;

	
	public static Log getLog() {
		return log;
	}

	private RoleService roleService;
	private MenuService menuService;
	private UserService userService;
	private LogService logService;
	private UserRole userRole;
	private UserRoleService userRolesService;
	public UserRoleService getUserRolesService() {
		return userRolesService;
	}
	public void setUserRolesService(UserRoleService userRolesService) {
		this.userRolesService = userRolesService;
	}

	public Long id;
	public Long roleid;
	public Long userids;
	
	public UserRole getUserRole() {
		return userRole;
	}
	public void setUserRole(UserRole userRole) {
		this.userRole = userRole;
	}
	public Long getRoleid() {
		return roleid;
	}
	public void setRoleid(Long roleid) {
		this.roleid = roleid;
	}
	public Long getUserids() {
		return userids;
	}
	public void setUserids(Long userids) {
		this.userids = userids;
	}

	private Long roleId;

	private Role role;

	private String menuIds;

	private String rolename;
	
	private Long parentid;
	
	private String treeId;
	
	private String rolelabel;
	
	private String roledesc;
	
	private String userid;
	
	private String username;
	
	private Long ids;
	
	public Long getIds() {
		return ids;
	}
	public void setIds(Long ids) {
		this.ids = ids;
	}
	public String getUserid() {
		return userid;
	}
	public void setUserid(String userid) {
		this.userid = userid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getRolelabel() {
		return rolelabel;
	}
	public void setRolelabel(String rolelabel) {
		this.rolelabel = rolelabel;
	}
	public String getRoledesc() {
		return roledesc;
	}
	public void setRoledesc(String roledesc) {
		this.roledesc = roledesc;
	}
	public String getTreeId() {
		return treeId;
	}
	public void setTreeId(String treeId) {
		this.treeId = treeId;
	}
	public Long getParentid() {
		return parentid;
	}
	public void setParentid(Long parentid) {
		this.parentid = parentid;
	}
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public Long getRoleId() {
		return roleId;
	}

	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}

	/*public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}*/

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public String getMenuIds() {
		return menuIds;
	}

	public void setMenuIds(String menuIds) {
		this.menuIds = menuIds;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setFgaService(FineGrainedAuthorityService fgaService) {
		this.fgaService = fgaService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	/*public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}*/

	public void setRows(int rows) {
		this.rows = rows;
	}


	public String getSidxs() {
		return sidxs;
	}
	public void setSidxs(String sidxs) {
		this.sidxs = sidxs;
	}
	public String getSord() {
		return sord;
	}

	public void setSord(String sord) {
		this.sord = sord;
	}

	public String getRolename() {
		return rolename;
	}

	public void setRolename(String rolename) {
		this.rolename = rolename;
	}

}
